package com.jxbeidou.system.api.exception;

import com.jxbeidou.core.enums.ResultCode;
import com.jxbeidou.core.exception.ServerException;
import com.jxbeidou.core.util.JsonUtil;
import feign.Response;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

import java.io.IOException;

/**
 * @program: jxbeidou-module
 * @ClassName: FeignClientErrorDecoder
 * @description: Feign全局异常处理
 * @author: 杜晓祥
 * @create: 2023-12-22 10:38
 * 版权所有：交信北斗(北京)信息科技有些公司
 */
@Configuration
@Slf4j
public class FeignClientErrorDecoder implements ErrorDecoder {
    @Override
    public Exception decode(String s, Response response) {
        log.error("[FeignClientErrorDecoder.decode]Feign请求出现异常, [{}]", s);
        HttpStatus status = HttpStatus.resolve(response.status());
        if (status != null) {
            if (status == HttpStatus.NOT_FOUND) {
                return new ServerException(ResultCode.NOT_FOUND_FAILED);
            }
            if (status == HttpStatus.FORBIDDEN) {
                return new ServerException(ResultCode.FORBIDDEN);
            }
            if (status == HttpStatus.INTERNAL_SERVER_ERROR) {
                return new ServerException(ResultCode.FAILED);
            }
            if (status == HttpStatus.SERVICE_UNAVAILABLE) {
                return new ServerException(ResultCode.FAILED);
            }
        }
        try {
            String json = JsonUtil.parseString(response.body().asInputStream());
            log.warn("json:[{}]", json);
            return new ServerException(json);
        } catch (IOException e) {
            throw new ServerException(ResultCode.FAILED);
        }
    }
}
